<script setup>
import { ref, onMounted } from 'vue'
import { io } from 'socket.io-client'
import { useRoute} from 'vue-router'


const $route = useRoute()
const { username } = $route.query
const socket = io("ws://127.0.0.1:3333/shareBoard");
const socketId=ref("")
socket.on("connect", () => {
    socketId.value=socket.id
});
socket.on("disconnect", () => {
    // console.log("socketio::"+socket.id)
});
const userMap = ref({})
socket.emit("init", { username })
socket.on("updateUser", (newUserMap) => {
    userMap.value = newUserMap
})

const canvasRef = ref()
onMounted(() => {
    const ctx = canvasRef.value.getContext("2d")
    ctx.strokeStyle = "black"
    ctx.lineWidth = 2
    let lastX = 0;
    let lastY = 0;
    let isDraw = false
    canvasRef.value.onmousedown = function (e) {
        isDraw = true
        lastX = e.offsetX
        lastY = e.offsetY
    }
    canvasRef.value.onmousemove = function (e) {
        if (!isDraw){
            return
        } 
        socket.emit('move',{lastX,lastY,offsetX:e.offsetX,offsetY:e.offsetY})
        ctx.beginPath()
        ctx.moveTo(lastX, lastY)
        ctx.lineTo(e.offsetX, e.offsetY)
        ctx.stroke()
        lastX = e.offsetX
        lastY = e.offsetY
    }
    canvasRef.value.onmouseup = function (e) {
        isDraw = false
    }
    socket.on("pushPointEveryone",({lastX,lastY,offsetX,offsetY,id})=>{
        if(id==socketId.value){
            return
        } 
        ctx.beginPath()
        ctx.moveTo(lastX, lastY)
        ctx.lineTo(offsetX, offsetY)
        ctx.stroke()
    })
})
</script>

<template>
    
    <div class="sharedoc_container">
        <h1 class="title">共享白板</h1>
        <div style="display: flex;flex:1">
            <ul style="width: 200px;">
                <li v-for="(value, key) in userMap" :key="key" class="user_title">{{ value }}</li>
            </ul>
            <div style="flex: 1;overflow: auto;">
                <canvas ref="canvasRef" style="background-color: #ccc;" width="400" height="400"></canvas>
            </div>
        </div>
    </div>
</template>

<style scoped lang='less'>
.sharedoc_container {
    height: 100vh;
    width: 99vw;
    display: flex;
    flex-direction: column;
    .title {
        width: 100%;
        height: 50px;
        line-height: 50px;
        font-size: 20px;
        font-weight: 800;
        text-align: center;
        background-color: #ccc;
    }
}
</style>